<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
<title>Javascript 二维码生成库：QRCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/FileSaver.js"></script>
<script type="text/javascript" src="./js/jszip.min.js"></script>
<script type="text/javascript" src="./js/qrcode.min.js"></script>
<script type="text/javascript" src="./js/axios.min.js"></script>

</head>
<body>
<input id="text" type="text" value="http://www.runoob.com" style="width:80%" /><br />
<div id="qrcode" style="width:200px; height:200px; margin-top:15px; margin: 0px auto; border: 25px solid rgb(255, 255, 255);"></div>

<button id="downBtn">下载</button>

<script type="text/javascript">

function getContent(url) {
  return new Promise((resolve, reject) => {
    axios({
      headers: {
        'Cache-control': 'no-cache'
      },
      url,
      method: 'GET',
      responseType: 'blob'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error)
    })
  })
}

function download(images, folderName) {
  const zip = new JSZip()
  const folder = zip.folder(folderName)
  const promises = images.map(image => {
    return getContent(image).then(data => {
      // 获取图片名
      const name = image.split('/')[image.split('/').length - 1]
      folder.file(name, data, { binary: true })
    })
  })
  Promise.all(promises).then(() => {
    zip.generateAsync({ type: 'blob' }).then(content => {
      saveAs(content, folderName)
    })
  })
}



/**
 * 获取图片的 base64 编码
 * @param image 图像对象
 * @return {string} 返回base64编码
 */
function getImageBase64(image) {
  const canvas = document.createElement('canvas')
  canvas.width = image.width
  canvas.height = image.height
  const ctx = canvas.getContext('2d')
  ctx.drawImage(image, 0, 0, image.width, image.height)
  // 获取图片后缀名
  const extension = image.src
    .substring(image.src.lastIndexOf('.') + 1)
    .toLowerCase()
  // 某些图片 url 可能没有后缀名，默认是 png
  return canvas.toDataURL('image/' + extension, 1)
}


var sourceList = [
      {
        id: 1,
        qrCode:
          'https://img1.baidu.com/it/u=3576008728,990949050&fm=253&fmt=auto&app=120&f=JPEG?w=900&h=800',
        picName: '图片1'
      },
      {
        id: 2,
        qrCode:
          'https://img.pconline.com.cn/images/upload/upc/tx/photoblog/1308/02/c11/24070074_24070074_1375457426078.jpg',
        picName: '图片2'
      }
    ];

/**
 * 批量下载图片
 * @param sourceList图像数据
 * @param zipName // 下载时的文件夹名称
 * @param sourceList[i].picName // 每张图片的名称--注意: 需要对数据属性进行转换
 */
function downloadZip (sourceList, zipName = '文件夹名称'){
  const zip = new JSZip()
  const fileFolder = zip.folder(zipName) // 创建 zipName 文件夹
  const fileList = []
  for (let i = 0; i < sourceList.length; i++) {
    const name = sourceList[i].picName // 注意: 每张图片的名称--需要对数据属性进行转换
    const image = new Image()
    image.setAttribute('crossOrigin', 'Anonymous') // 设置 crossOrigin 属性，解决图片跨域报错
    image.src = sourceList[i].qrCode
    image.onload = async() => {
      const url = await getImageBase64(image)
      fileList.push({ name: name, img: url.substring(22) }) // 截取 data:image/png;base64, 后的数据
      if (fileList.length === sourceList.length) {
        if (fileList.length) {
          for (let k = 0; k < fileList.length; k++) {
          	// 往文件夹中，添加每张图片数据
            fileFolder.file(fileList[k].name + '.png', fileList[k].img, {
              base64: true
            })
          }
          zip.generateAsync({ type: 'blob' }).then(content => {
			saveAs(content, zipName + '.zip')
          })
        }
      }
    }
  }
}


var qrcode = new QRCode(document.getElementById("qrcode"), {
	// text: qrCodeContent,   // 二维码内容
	width: 128,  
	height: 128,
	colorDark : "#000000",  // 码的颜色
	colorLight : "#ffffff",  // 码的背景色
	correctLevel : QRCode.CorrectLevel.H,  // 高度容错
});

function makeCode () {		
	var elText = document.getElementById("text");
	if (!elText.value) {
		alert("Input a text");
		elText.focus();
		return;
	}
	// qrcode.clear(); // 可以清除二维码
	qrcode.makeCode(elText.value);
}

makeCode();

$("#text").
	on("blur", function () {
		makeCode();
	}).
	on("keydown", function (e) {
		if (e.keyCode == 13) {
			makeCode();
		}
	});

$("#downBtn").on("click", function(){
    //const qrCodeDiv = document.getElementById('qrcode');  // 找到二维码div
    //const url = qrCodeDiv.querySelector('canvas').toDataURL('image/png');          // 获取图片地址
  	//const a = document.createElement('a');          // 创建一个a节点插入的document
    //const handle = new MouseEvent('click')           // 模拟鼠标click点击事件
    //a.download = "1112233";                // 设置a节点的download属性值
    //a.href = url;                                 // 将图片的src赋值给a节点的href
    //a.dispatchEvent(handle)            // 触发点击
    
    downloadZip (sourceList, '文件夹名称');
    
})

</script>
</body>
</html>